package com.hwtx.form.domain.ds;

import lombok.Getter;
import org.jetbrains.annotations.NotNull;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Getter
public class DynamicDataSource extends AbstractRoutingDataSource {

    private Map<Object, Object> targetDataSources = new HashMap<>();

    @Override
    protected Object determineCurrentLookupKey() {
        return DataSourceContextHolder.getDataSourceKey();
    }

    public void setTargetDataSources(@NotNull Map<Object, Object> targetDataSources) {
        this.targetDataSources = targetDataSources;
        super.setTargetDataSources(targetDataSources);
        super.afterPropertiesSet(); // 刷新数据源
    }

    /**
     * 添加一个新的数据源
     *
     * @param key        数据源的标识符
     * @param dataSource 数据源对象
     */
    public void addTargetDataSource(String key, DataSource dataSource) {
        targetDataSources.put(key, dataSource);
        super.setTargetDataSources(targetDataSources);
        super.afterPropertiesSet(); // 刷新数据源
    }

    /**
     * 删除一个已有的数据源
     *
     * @param key 数据源的标识符
     */
    public void removeTargetDataSource(String key) {
        if (targetDataSources.containsKey(key)) {
            targetDataSources.remove(key);
            super.setTargetDataSources(targetDataSources);
            super.afterPropertiesSet(); // 刷新数据源
        }
    }
}